package com.gavinnie.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @ClassName: CookieUtil
* @Description: TODO(CookieUtil工具类)
* @author Gavin Nie
* @e-mail Gavin_Nie@163.com
* @date 2014年9月7日 上午10:35:40
*/ 
public class CookieUtil {
	private static final int MAXTIME = 60*60*24*7;	//最长cookie保存一个星期 
	
	public static void addCookie(String username,String password,String checkbox,HttpServletRequest request, HttpServletResponse response){
		String path = request.getContextPath()+"/";
		
		System.out.println("cookiePath:"+path);
		
		//对用户名,密码进行加密
		try {
			//可以自己设定加密规则,见EncryptionCode中的encryptionRules
			username = EncryptionCoder.encryptBASE64(username.getBytes());
			password = EncryptionCoder.encryptBASE64(password.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//创建cookie
		Cookie usernameCookie = new Cookie("username",username );
		Cookie passwordCookie = new Cookie("password", password);
		
		//设置cookie路径
		usernameCookie.setPath(path);
		passwordCookie.setPath(path);
		
		if(checkbox == null){	//复选框没有勾上,不保存账号密码
			usernameCookie.setMaxAge(0);
			passwordCookie.setMaxAge(0);
		}else{					//保存账户密码,设置时长
			usernameCookie.setMaxAge(MAXTIME);
			passwordCookie.setMaxAge(MAXTIME);
		}
		
		//添加cookie
		response.addCookie(usernameCookie);
		response.addCookie(passwordCookie);
	}
}
